package com.lcm.jnode.model;

import java.util.Date;

import org.apache.commons.codec.digest.DigestUtils;

import com.jfinal.plugin.activerecord.Model;

/**
 * 用户表
 * @author 春梦
 *
 */
public class User extends Model<User>{

	private static final long serialVersionUID = 4049101852276240918L;
	private static final String PHOTO_URL = "http://www.gravatar.com/avatar/";
	
	public static final User dao = new User();
	
	public static final String ID = "id";								// id
	public static final String NICK_NAME = "nick_name";					// 网名
	public static final String PASSWORD = "password";					// 密码
	public static final String EMAIL = "email";							// 邮箱
	public static final String EMAIL_VERIFY = "email_verify";			// 邮箱校验      默认：0 通过：1
	public static final int EMAIL_N = 0;								// 邮箱校验      默认：0 
	public static final int EMAIL_Y = 1;								// 邮箱校验      通过：1
	public static final String HEAD_PHOTO = "head_photo";				// 头像
	public static final String SEX = "sex";								// 性别		 默认：0 女   男：1 
	public static final String BIRTHDAY = "birthday";					// 生日		
	public static final String STATUS = "status";						// 是否登录状态  默认：0 在线：1
	public static final String LAST_LOGIN_TIME = "last_login_time";		// 最后登录时间
	public static final String SIGNATURE = "signature";					// 个性签名
	public static final String URL = "url";								// 网站
	public static final String LIVENESS = "liveness";					// 活跃度
	public static final String CONTRIBUTION = "contribution";			// 贡献
	public static final String AUTHORITY = "authority";					// 权限     默认：0  vip：1  admin：2
	public static final String DEL_STATUS = "del_status";				// 是否删除 默认：0  删除：1 
	public static final String CREATE_TIME = "create_time"; 			// 添加时间
	public static final String UPDATE_TIME = "update_time"; 			// 更新时间

	// 添加用户的统一处理
	public User saveUser(String email, String name) {
		User user = new User();
		user.set(EMAIL, email);
		user.set(NICK_NAME, name);
		user.set(PASSWORD, DigestUtils.md5Hex(System.currentTimeMillis() + ""));
		// avatar 头像
		user.set(HEAD_PHOTO, PHOTO_URL + DigestUtils.md5Hex(email.trim()));
		user.set(EMAIL_VERIFY, 1);  	// 第三方登陆注册的直接放行 貌似这样做不够好
		user.set(CREATE_TIME, new Date());
		user.set(UPDATE_TIME, new Date());
		boolean temp = user.save();
		return temp ? user : null;
	}
	
	// 更新用户的统一处理
	public void updateUser(User user){
		user.set(UPDATE_TIME, new Date()).update();
	}
	
	// 用户登录
	public User login(String email, String pwd){
		return dao.findFirst("select * from user_info where email = ? and password = ? and email_verify = 1 and del_status = 0 limit 1", email, pwd);
	}
	
	// 根据邮箱查找
	public User findByEmail(String mailTo) {
		String sql = "select u.id, u.nick_name from user_info u where u.email = ? and u.email_verify = 1 and u.del_status = 0 limit 1";
		return dao.findFirst(sql, mailTo);
	}

	// 根据id和状态
	public User findByIdStatus(Integer id) {
		String sql = "select u.* from user_info u where u.id = ? and u.email_verify = 1 and u.del_status = 0 limit 1";
		return dao.findFirst(sql, id);
	}
}
